<?php

require_once("database_api.php");
require_once("utilites_inc.php");

class forum_api
{
	private $db;
	
	public function __construct($db) 
	{
		$this->db = $db;
    }
	
	
	public function get_comment_list($project_id, $page)
	{
		$sql = $this->db->safeQuery("SELECT CMT_TEXT, USR_ID, USR_NAME, USR_IMAGE, CMT_DATE FROM comments"
		. " INNER JOIN users on USR_ID = CMT_USR_ID"
		. " WHERE CMT_PRJ_ID = {0}"
		. " ORDER BY CMT_DATE DESC LIMIT {1}, {2}", $project_id, $page * MAX_VIEW_FORUM_COMMENTS, MAX_VIEW_FORUM_COMMENTS);
		
		return $this->db->query($sql);
	}	
	
	public function get_comments_count($project_id)
	{
		$sql = $this->db->safeQuery("SELECT COUNT(CMT_ID) AS COMMENT_COUNT FROM comments WHERE CMT_PRJ_ID = {0}", $project_id);
		
		if($result = $this->db->query($sql))
		{
			$row = $result->fetch_assoc();
			$result->free();
			
			if($row)
			{
				return $row["COMMENT_COUNT"];
			}			
		}
	}
	
	
	public function add_comment($project_id, $user_id, $text)
	{
		$transform_comment = htmlEscapeAndLinkUrls($text);
		
		$sql = $this->db->safeQuery("INSERT INTO comments (CMT_USR_ID, CMT_TEXT, CMT_DATE, CMT_PRJ_ID) VALUES({0}, '$transform_comment', now(), {1})", $user_id, $project_id);
		
		if($this->db->query($sql) === TRUE)
		{
			return $this->db->getLastID();
		}
	}
	
	public function get_comment($comment_id)
	{
		$sql = $this->db->safeQuery("SELECT USR_NAME, CMT_USR_ID, CMT_TEXT, CMT_DATE FROM comments"
		. " INNER JOIN users ON USR_ID = CMT_USR_ID"
		. " WHERE CMT_ID = {0} LIMIT 1", $comment_id);
		
		if($result = $this->db->query($sql))
		{
			$row = $result->fetch_assoc();
			$result->free();
			
			return $row;
		}
	}
}